import time
import paramiko
from md2html import write_html
from configparser import ConfigParser
import sys
import getopt


def print_time(f):
    def method(*args):
        start = time.time()
        print("%s " % time.strftime("%x %X"), end='开始推送...\n')
        f(*args)
        end = time.time()
        print("推送成功！本次推送花费时间:%.2f秒。" % (end-start))
    return method


@print_time
def ssh_scp_put(ip: str, port: int, user: str, password: str, local_file: str, remote_file: str):
    """
    :param ip: 服务器ip地址
    :param port: 端口(22)
    :param user: 用户名
    :param password: 用户密码
    :param local_file: 本地文件地址
    :param remote_file: 要上传的文件地址（例：/test.txt）
    :return: 
    """
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(ip, port, user, password)

    sftp = ssh.open_sftp()
    sftp.put(local_file, remote_file)


def main():
    cfg = ConfigParser()
    cfg.read("config.ini", encoding='gbk')
    db_cfg = dict(cfg.items("localdb"))
    db_cfg['port'] = int(db_cfg['port'])
    write_html()
    ssh_scp_put(*db_cfg.values())


if __name__ == "__main__":
    # 初始化参数
    inputfile = '../mysite/index.html'
    outputfile = '/usr/local/webserver/nginx/html/index.html'
    try:
        opts, args = getopt.getopt(sys.argv[1:], "hi:o:", ["ifile=", "ofile="])
    except getopt.GetoptError:
        print('upload.py -i <inputfile> -o <outputfile>')
        sys.exit(2)

    # 无命令行参数的情况
    if not opts:
        main()
        sys.exit(0)

    for opt, arg in opts:
        if opt == '-h':
            print('upload.py -i <inputfile> -o <outputfile>')
            sys.exit()
        elif opt in ("-i", "--ifile"):
            inputfile = arg
           
        elif opt in ("-o", "--ofile"):
            outputfile = arg

    # 如果是md文件，先生成后上传
    if inputfile.endswith('md'):
        html_path = inputfile.replace(".md",'.html')
        write_html(md_path = inputfile,html_path = html_path)
        # 将输入文件替换为生成后的html路径
        inputfile = html_path
        # 输出路径
        outputfile = outputfile.replace('index.html', inputfile)


    cfg = ConfigParser()
    cfg.read("config.ini", encoding='gbk')
    db_cfg = dict(cfg.items("localdb"))

    ip = db_cfg['host']
    port = db_cfg['port']
    user = db_cfg['user']
    password = db_cfg['password'] 
    ssh_scp_put(ip, port, user, password, inputfile, outputfile)
